package cn.mhome.merchant.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

/**
 * 时间工具类
 * 
 * @author 吕鹏
 */
public class DateUtilInner {

	public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public SimpleDateFormat generalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
	public SimpleDateFormat minuteFormat = new SimpleDateFormat("HH时mm分");
	public SimpleDateFormat dayTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

	public DateUtilInner() {

	}

	/**
	 * 获取操作时间 lvpeng
	 * 
	 * @return
	 */
	public Date getOperateTime() {
		return new Date(System.currentTimeMillis());
	}

	/**
	 * 项目周期
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 */
	public String getProjectCycle(Date time1, Date time2) {
		String temp1 = "";
		if (time1 != null) {
			temp1 = generalFormat.format(time1);
		}
		String temp2 = "";
		if (time2 != null) {
			temp2 = generalFormat.format(time2);
		}
		return temp1 + " ~ " + temp2;
	}

	/**
	 * 获取相隔interval天的时间 并返回pattern类型的string
	 * 
	 * @param interval
	 * @param starttime
	 * @param pattern
	 * @return
	 */
	public String getDate(String interval, Date starttime, String pattern) {
		Calendar temp = Calendar.getInstance(TimeZone.getDefault());
		temp.setTime(starttime);
		temp.add(Calendar.DATE, Integer.parseInt(interval));
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(temp.getTime());
	}

	/**
	 * 格式化日期
	 */
	public String getNowByFormat(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String dd = "";
		try {
			dd = sdf.format(new Date());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dd;
	}

	/**
	 * 将字符串类型转换为时间类型 如果传递过来的字符串为 yyyy-mm-dd hh:mm 则自动补全 :ss
	 * 
	 * @param str
	 * @return
	 */
	public Date str2Date(String str) {
		if (null == str) {
			return null;
		}
		if (str != null && str.length() == 16) {
			str = str + ":00";
		}
		Date d = null;
		SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN);
		try {
			d = sdf.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return d;
	}

	/**
	 * 将字符串按照pattern类型转换为时间类型
	 * 
	 * @param str
	 * @param pattern
	 * @return
	 */
	public Date str2Date(String str, String pattern) {
		Date d = null;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			d = sdf.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return d;
	}

	/**
	 * 将时间格式化
	 * 
	 * @return
	 */
	public Date datePattern(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN);
		try {
			String dd = sdf.format(date);
			date = str2Date(dd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 将long转成时间格式
	 * 
	 * @param datelong
	 * @param format
	 * @return
	 */
	public String long2date(long datelong, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = new Date();
		date.setTime(datelong);
		return sdf.format(date);
	}

	/**
	 * 将时间格式化
	 */
	public Date datePattern(Date date, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			String dd = sdf.format(date);
			date = str2Date(dd, pattern);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 将date转换成默认时间格式的字符串
	 * 
	 * @param date
	 * @return
	 */
	public String date2Str(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN);
		return sdf.format(date);
	}

	/**
	 * 将date转换成format格式的字符串
	 * 
	 * @param date
	 * @return
	 */
	public String date2Str(Date date, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	/**
	 * 获取昨天
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public Date getLastDate(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);

		calendar.add(Calendar.DATE, -1);

		return str2Date(date2Str(calendar.getTime()));
	}
	
	/**
	 * 获取昨天
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 * @throws Exception
	 */
	public String getLastDate(Date date, String pattern) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		calendar.add(Calendar.DATE, -1);
		return date2Str(calendar.getTime(), pattern);
	}
	
	/**
	 * 获取前天
	 * @param date
	 * @param pattern
	 * @return
	 */
	public String getTheDayBeforeYesterday(Date date, String pattern) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		calendar.add(Calendar.DATE, -2);
		return date2Str(calendar.getTime());
	}

	/**
	 * 获取上周第一天（周一）
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public Date getLastWeekStart(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		int startnum = 0;
		if (i == 0) {
			startnum = 7 + 6;
		} else {
			startnum = 7 + i - 1;
		}
		calendar.add(Calendar.DATE, -startnum);

		return str2Date(date2Str(calendar.getTime()));
	}

	/**
	 * 返回指定月的最后一天 比如 201002 获取2月的最后一天
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public int getLastDayOfMonth(int year, int month) {
		Calendar calendar = Calendar.getInstance();

		calendar.set(Calendar.YEAR, year);

		calendar.set(Calendar.MONTH, month);//

		calendar.set(Calendar.DATE, 1);

		calendar.add(Calendar.DATE, -1);

		int end = calendar.get(Calendar.DATE);
		return end;
	}

	/**
	 * 获取上周最后一天（周末）
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public Date getLastWeekEnd(Date date) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		calendar.setTime(date);
		int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		int endnum = 0;
		if (i == 0) {
			endnum = 7;
		} else {
			endnum = i;
		}
		calendar.add(Calendar.DATE, -(endnum - 1));

		return str2Date(date2Str(calendar.getTime()));
	}

	/**
	 * 改更现在时间
	 */
	public Date changeDate(String type, int value) {
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
		if (type.equals("month")) {
			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + value);
		} else if (type.equals("date")) {
			calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + value);
		}
		return calendar.getTime();
	}

	/**
	 * 更改时间
	 */
	public Date changeDate(Date date, String type, int value) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		if (type.equals("month")) {
			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + value);
		} else if (type.equals("date")) {
			calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + value);
		} else if (type.endsWith("year")) {
			calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + value);
		}
		return calendar.getTime();
	}

	/**
	 * 比较时间是否在这两个时间点之间
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 */
	public boolean checkTime(String time1, String time2) {
		Calendar calendar = Calendar.getInstance();
		Date date1 = calendar.getTime();
		Date date11 = str2Date(date2Str(date1, "yyyy-MM-dd") + " " + time1);// 起始时间

		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, 1);
		Date date2 = c.getTime();
		Date date22 = str2Date(date2Str(date2, "yyyy-MM-dd") + " " + time2);// 终止时间

		Calendar scalendar = Calendar.getInstance();
		scalendar.setTime(date11);// 起始时间

		Calendar ecalendar = Calendar.getInstance();
		ecalendar.setTime(date22);// 终止时间

		Calendar calendarnow = Calendar.getInstance();

		return (calendarnow.after(scalendar) && calendarnow.before(ecalendar));

		// if (calendarnow.after(scalendar) && calendarnow.before(ecalendar)) {
		// return true;
		// } else {
		// return false;
		// }

	}

	/**
	 * 检查输入日期是否是interval月之内的日期
	 * 
	 * @param time
	 * @param interval
	 * @return
	 */
	public boolean checkOnly6Month(String time, int interval) {
		boolean t = true;
		Calendar calendarnow = Calendar.getInstance();
		Date datetmp = str2Date(time + " 00:00:01");
		Calendar scalendar = Calendar.getInstance();
		scalendar.setTime(datetmp);// 要判断的时间点
		calendarnow.add(Calendar.MONTH, interval); // 将当前日期前翻interval个月
		calendarnow.set(Calendar.DAY_OF_MONTH, 1);// 将当前日期前翻interval个月之后
		// 将日期翻到该月第一天
		calendarnow.set(Calendar.HOUR_OF_DAY, 0);
		calendarnow.set(Calendar.MINUTE, 0);
		calendarnow.set(Calendar.SECOND, 0);

		if (!scalendar.after(calendarnow)) {
			t = false;
		}
		return t;
	}

	/**
	 * 计算两个日期相隔的天数
	 * 
	 * @param firstString
	 * @param secondString
	 * @return
	 */
	public int nDaysBetweenTwoDate(String starttime, String endtime) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date firstDate = null;
		Date secondDate = null;
		try {
			firstDate = df.parse(starttime);
			secondDate = df.parse(endtime);
		} catch (Exception e) {
			e.printStackTrace();
			// 日期型字符串格式错误
		}
		int nDay = (int) ((secondDate.getTime() - firstDate.getTime()) / (24 * 60 * 60 * 1000));
		return nDay;
	}

	/**
	 * 计算两个日期相隔的天数
	 * 
	 * @param firstString
	 * @param secondString
	 * @return
	 */
	public int nDaysBetweenTwoDate(Date startTime, Date endTime) {
		int nDay = (int) ((endTime.getTime() - startTime.getTime()) / (24 * 60 * 60 * 1000));
		return nDay;
	}


	/**
	 * 获取当月第一天和下月第一天
	 * 
	 * @return
	 */
	public List<Date> getFirstAndLastDayOfMonth() {
		List<Date> listDate = new ArrayList<Date>();
		// 获取当前日期 并设置0时0分0秒
		Calendar cal_now = Calendar.getInstance();
		cal_now.set(Calendar.HOUR_OF_DAY, 0);
		cal_now.set(Calendar.MINUTE, 0);
		cal_now.set(Calendar.SECOND, 0);
		// 设置为1号,当前日期既为本月第一天
		cal_now.set(Calendar.DAY_OF_MONTH, 1);
		listDate.add(cal_now.getTime());
		// 设置为下月1号
		cal_now.add(Calendar.MONTH, 1);
		listDate.add(cal_now.getTime());
		return listDate;
	}

	/**
	 * 获取今天和昨天开始时间
	 * 
	 * @return
	 */
	public List<Date> getLastDayAndToday() {
		List<Date> listDate = new ArrayList<Date>();
		// 获取当前日期 并设置0时0分0秒
		Calendar cal_now = Calendar.getInstance();
		cal_now.set(Calendar.HOUR_OF_DAY, 0);
		cal_now.set(Calendar.MINUTE, 0);
		cal_now.set(Calendar.SECOND, 0);
		listDate.add(cal_now.getTime());
		// 设置到昨天
		cal_now.add(Calendar.DATE, -1);
		listDate.add(cal_now.getTime());
		return listDate;
	}

	/**
	 * 获取今天和明天开始时间
	 * 
	 * @return
	 */
	public List<Date> getCurDayAndTomorrowDay() {
		List<Date> listDate = new ArrayList<Date>();
		// 获取当前日期 并设置0时0分0秒
		Calendar cal_now = Calendar.getInstance();
		cal_now.set(Calendar.HOUR_OF_DAY, 0);
		cal_now.set(Calendar.MINUTE, 0);
		cal_now.set(Calendar.SECOND, 0);
		listDate.add(cal_now.getTime());
		// 设置第二天
		cal_now.add(Calendar.DAY_OF_MONTH, 1);
		listDate.add(cal_now.getTime());
		return listDate;
	}

	/**
	 * 获取当前时间小时和下个小时
	 * 
	 * @return
	 */
	public List<Date> getCurHourAndNextHour() {
		List<Date> listDate = new ArrayList<Date>();
		// 获取当前小时并设置0分0秒
		Calendar cal_now = Calendar.getInstance();
		cal_now.set(Calendar.MINUTE, 0);
		cal_now.set(Calendar.SECOND, 0);
		listDate.add(cal_now.getTime());
		// 设置下个小时
		cal_now.add(Calendar.HOUR_OF_DAY, 1);
		listDate.add(cal_now.getTime());
		return listDate;
	}

	/**
	 * 获取当前时间距离结束时间毫秒数
	 * 
	 * @param toDate
	 * @return
	 */
	public long getNowInteval(Date toDate) {
		return toDate.getTime() - System.currentTimeMillis();
	}

	/**
	 * 比较当前时间是否比原时间最多相差一分钟
	 * 
	 * @param d
	 *            原时间
	 * @return
	 */
	public boolean checkOneMinute(Date d) {
		boolean b = false;
		long num = System.currentTimeMillis() - d.getTime();
		if (num <= 60000)
			b = true;
		return b;
	}

	/**
	 * 比较当前时间和原时间是否在同一天
	 * 
	 * @param d
	 * @return
	 */
	public boolean isTheSameDay(Date d) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(d);
		c2.setTime(new Date());
		return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH))
				&& (c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH));
	}

	/**
	 * 判断当前时候是否是忙时 是返回true 反之 false ||请求时间与2取摸 整出的返回true 反之false
	 * 
	 * @return
	 */
	public boolean checkHotTime() {
		boolean b = false;
		// Calendar ca = Calendar.getInstance();
		// int hour = ca.get(Calendar.HOUR);// 小时
		// if ((hour >= 8 && hour <= 11) || (hour >= 13 && hour <= 18)) {
		// b = true;
		// }
		Long s = System.currentTimeMillis();
		if (s % 2 == 0) {
			b = true;
		}
		return b;
	}

	public long getUTCFromDateStr(String time, String format) {
		long descTime = 0L;
		Date date = null;
		try {
			date = new SimpleDateFormat(StringUtils.isEmpty(format) ? DEFAULT_PATTERN : format).parse(time);
			descTime = date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return descTime;
	}


	/**
	 * 判断当前日期是星期几
	 * 
	 * 修要判断的时间
	 * 
	 * @return dayForWeek 判断结果
	 * @Exception 发生异常
	 */
	public int getDayForWeek(Date date) throws Exception {
		int dayForWeek = 0;
		if (date != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			if (c.get(Calendar.DAY_OF_WEEK) == 1) {
				dayForWeek = 7;
			} else {
				dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
			}
		}
		return dayForWeek;
	}

	public String[] getWeekDate(Date date) {
		if (date == null)
			date = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
		String[] str = new String[2];
		str[0] = df.format(date);
		str[1] = df.format(cal.getTime());
		return str;
	}

	/**
	 * 当前时间+(正负数)
	 * 
	 * @param date
	 * @param days
	 * @return
	 */
	public Date modifyDate(Date date, int hour, int min) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		// calendar.add(Calendar.DATE,days);
		calendar.add(Calendar.HOUR, hour);
		calendar.add(Calendar.MINUTE, min);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 当前时间+(正负数)
	 * 
	 * @param date
	 * @param days
	 * @return
	 */
	public Date modifyDate(Date date, int day) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, day);
		date = calendar.getTime();
		return date;
	}

	// public static void main(String[] args) {
	// DateUtilInner dateUtilInner = new DateUtilInner();
	// Date tomcat = dateUtilInner.modifyDate(new Date(),1);
	// System.out.println(dateUtilInner.date2Str(date));
	// }

	/**
	 * 
	 */

	/**
	 * 获取操作时间
	 * 
	 * @return
	 */
	public String formatDate(Date date) {
		return dateFormat.format(date);
	}

	/**
	 * 通过两个日期 得到两个日期的周期
	 * 
	 * @return 2014-05-07~2014-05-09
	 */
	public String getSaleCycle(Date time1, Date time2) {
		String temp1 = "";
		if (time1 != null) {
			temp1 = generalFormat.format(time1);
		}
		String temp2 = "";
		if (time2 != null) {
			temp2 = generalFormat.format(time2);
		}
		return temp1 + " ~ " + temp2;
	}

	/**
	 * 第一个时间小于第二个时间 返回true
	 */
	public boolean compareTime(Date oneTime, Date twoTime) {
		return twoTime.getTime() > oneTime.getTime();
	}

	/**
	 * 再一组Long集合中找到最小值和最大值
	 * 
	 * @return
	 */
	public List<Long> findMinAndMaxValue(List<Long> values) {
		List<Long> valueLust = new ArrayList<Long>();
		Long min = null;
		Long max = null;
		if (values != null && values.size() > 0) {
			for (Long t : values) {
				if (min == null) {
					min = t;
				} else {
					min = min.compareTo(t) < 0 ? min : t;
				}
			}
			valueLust.add(min);
			for (Long t : values) {
				if (max == null) {
					max = t;
				} else {
					max = max.compareTo(t) > 0 ? max : t;
				}
			}
			valueLust.add(max);
		}
		return valueLust;
	}

	/**
	 * 获取24小时以后的时间
	 * 
	 * @param today
	 * @return
	 */
	public Date getTomorrowByToday(Date today) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(today);
		calendar.add(Calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
		Date tomorrow = new Date(calendar.getTimeInMillis()); // 这个时间就是日期往后推一天的结果
		return tomorrow;
	}
	
	/**
	 * 获取几day后的日期
	 * @param today
	 * @param day
	 * @param df
	 * @return
	 */
	public String getNextDay(Date today, int day, String df) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(today);
		calendar.add(Calendar.DATE, day);// 把日期往后增加一天.整数往后推,负数往前移动
		return date2Str(calendar.getTime(),df);
	}

	/**
	 * 根据今天获取本日，本周，本月的开始时间
	 * 
	 * @param today
	 * @return
	 */
	public String[] getThreeDateByToday(Date today) {
		String[] dates = new String[3];
		Calendar cal = Calendar.getInstance();
		dates[0] = dayFormat.format(new Date(System.currentTimeMillis())) + " 00:00:00";
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		dates[1] = dayFormat.format(cal.getTime()) + " 00:00:00";
		cal.set(Calendar.DAY_OF_MONTH, 1);
		dates[2] = dayFormat.format(cal.getTime()) + " 00:00:00";
		return dates;
	}

	/***
	 * TimeStamp转换成字符串
	 * 
	 * @param time
	 * @param dateFormat
	 * @return
	 */
	public String getTimeStampString(Timestamp time, SimpleDateFormat dateFormatParam) {
		if (null != time) {
			try {
				if (null == dateFormatParam) {
					dateFormatParam = dateFormat;
				}
				return dateFormat.format(time);
			} catch (Exception e) {

			}
		}
		return null;
	}

	public Date changeDateByDay(Date date, int day) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, day);// 把日期往后增加一天.整数往后推,负数往前移动
		date = calendar.getTime(); // 这个时间就是日期往后推一天的结果
		return date;
	}

	/**
	 * 获取两天时间差
	 * 
	 * @param smdate
	 * @param bdate
	 * @return
	 */
	public int daysBetween(Date smdate, Date bdate) {
		long between_days = 0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			smdate = sdf.parse(sdf.format(smdate));
			bdate = sdf.parse(sdf.format(bdate));
			Calendar cal = Calendar.getInstance();
			cal.setTime(smdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(bdate);
			long time2 = cal.getTimeInMillis();
			between_days = (time2 - time1) / (1000 * 3600 * 24);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return Integer.parseInt(String.valueOf(between_days));
	}
}
